package com.self.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.self.commonutils.R;
import com.self.servicebase.handler.MyException;
import com.self.vod.service.VodService;
import com.self.vod.utils.ConstantPropertiesUtil;
import com.self.vod.utils.InitVodClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.ws.rs.Path;
import java.util.List;

@Api(description = "阿里云的视频点播服务")
@CrossOrigin
@RestController
@RequestMapping("/eduvod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    //上传视频到阿里云
    @ApiOperation(value = "上传视频到阿里云")
    @PostMapping("uploadVideo")
    public R uploadVideo(
            @ApiParam(name = "file",value = "视频文件",required = true) MultipartFile file){
        //返回视频的Id值
        System.out.println(file.getOriginalFilename());
        String videoId = vodService.uploadVideo(file);
        return R.ok().data("videoId",videoId);
    }

    //根据视频ID删除阿里云视频
    @DeleteMapping("removeVideo/{videoId}")
    public R removeVideo(@PathVariable("videoId") String videoId){

        vodService.removeVideo(videoId);
        return R.ok();

    }

    //删除多个阿里云视频的方法
    //传入多个视频ID
    @DeleteMapping("delete-batch")
    public R deleteBatch(@RequestParam("videoList") List<String> videoList){

        vodService.batchRemoveVideo(videoList);
        return R.ok();
    }

    //根据视频Id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable("id") String id){
        try {
            //1. 创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_SECRET);
            //2. 创建获取凭证的request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
            //3.向request中设置id
            request.setVideoId(id);
            //4.调用方法得到凭证
            response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        }catch (Exception e){
            throw new MyException(20001,"获取凭证失败~~");
        }
    }

}
